package com.qfedu.fmmall.service.impl;

import com.qfedu.fmmal.vo.ResStatus;
import com.qfedu.fmmal.vo.ResultVO;
import com.qfedu.fmmall.dao.OrderItemMapper;
import com.qfedu.fmmall.dao.OrdersMapper;
import com.qfedu.fmmall.dao.ProductSkuMapper;
import com.qfedu.fmmall.dao.ShoppingCartMapper;
import com.qfedu.fmmall.entity.OrderItem;
import com.qfedu.fmmall.entity.Orders;
import com.qfedu.fmmall.entity.ProductSku;
import com.qfedu.fmmall.entity.VO.ShoppingCartVO;
import com.qfedu.fmmall.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.annotation.Order;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private ProductSkuMapper productSkuMapper;

    //保存订单业务
    @Transactional//事务
    public Map<String,String> addOrder(String cids,Orders order) throws SQLException{
        Map<String,String> map = new HashMap<>();

        //1.根据cids查询当前订单中关联的购物车记录详情（包括库存）
        String[] arr = cids.split(",");
        List<Integer> cidsList = new ArrayList<>();
        for (int i=0; i<arr.length;i++){
            cidsList.add(Integer.parseInt(arr[i]));
        }
        List<ShoppingCartVO> list = shoppingCartMapper.selectShopcartByCids(cidsList);

        //2.校验库存
        boolean f = true;
        String untitled = "";
        for (ShoppingCartVO sc:list){
            if (Integer.parseInt( sc.getCartNum() )>sc.getSkuStock()){
                f=false;
                //break;
            }
            //获取所有商品的名称，以“，”分割拼接成字符串
            untitled = untitled + sc.getProductName() + "  ";
        }
        if (f){
            //3.表示用户充足----------保存订单
            order.setUntitled(untitled);
            order.setCreateTime(new Date());
            order.setStatus("1");
            //生成订单编号
            String orderId = UUID.randomUUID().toString().replace("-", "");
            order.setOrderId(orderId);

            //4.保存订单
            ordersMapper.insert(order);
            //if (i>0){
                //生成商品快照
                //List<OrderItem> orderItems = new ArrayList<>();
            for (ShoppingCartVO sc:list){
                int cnum = Integer.parseInt(sc.getCartNum());
                String itemId = System.currentTimeMillis()+""+ (new Random().nextInt(89999)+10000 );
                OrderItem orderItem = new OrderItem(itemId, orderId, sc.getProductId(), sc.getProductName(), sc.getProductImg(),
                        sc.getSkuId(), sc.getSkuName(),new BigDecimal(sc.getSellPrice()) , cnum,
                        new BigDecimal(sc.getSellPrice() * cnum) , new Date(), new Date(), 0);
                //orderItems.add(orderItem);
                orderItemMapper.insert(orderItem);
            }
            //int j = orderItemMapper.insertList(orderItems);

            //5.扣减库存
            for (ShoppingCartVO sc:list){
                String skuId = sc.getSkuId();
                int newStock = sc.getSkuStock() - Integer.parseInt(sc.getCartNum());

//                    Example example = new Example(ProductSku.class);
//                    Example.Criteria criteria = example.createCriteria();
//                    criteria.andEqualTo("skuId",skuId);

//                    ProductSku productSku = productSkuMapper.selectByPrimaryKey(skuId);
//                    //ProductSku productSku = new ProductSku();
//                    productSku.setStock(newStock);
//                    int k = productSkuMapper.updateByPrimaryKey(productSku);

                ProductSku productSku = new ProductSku();
                productSku.setSkuId(skuId);
                productSku.setStock(newStock);
                productSkuMapper.updateByPrimaryKeySelective(productSku);

            }

            //6.删除购物车:当购物车中的记录购买成功后，购物车对应做删除操作
            for (int cid:cidsList){
                shoppingCartMapper.deleteByPrimaryKey(cid);
            }

            map.put("orderId",orderId);
            map.put("productNames",untitled);

            return map;

        }else {
            //表示库存不足
            return null;
        }

    }

    @Override
    public int updateOrderStatus(String orderId, String status) {
        Orders orders = new Orders();
        orders.setOrderId(orderId);
        orders.setStatus(status);
        int i = ordersMapper.updateByPrimaryKeySelective(orders);
        return i;
    }

    @Override
    public ResultVO GetOrderById(String orderId) {
        Orders orders = ordersMapper.selectByPrimaryKey(orderId);

        return new ResultVO(ResStatus.OK,"success", orders.getStatus());
    }

    @Override
    @Transactional(isolation = Isolation.SERIALIZABLE)
    public void closeOrder(String orderId) {
        synchronized (this) {
            // b.修改当前订单status=6（订单关闭），close_type=1（超时未支付）,
            Orders cancleOrder = new Orders();
            cancleOrder.setOrderId(orderId);
            cancleOrder.setStatus("6");
            cancleOrder.setCloseType(1);
            ordersMapper.updateByPrimaryKeySelective(cancleOrder);

            // c.还原库存：先根据当前订单编号查询商品快照（skuid buy_count）--->修改product_sku
            Example example1 = new Example(OrderItem.class);
            Example.Criteria criteria1 = example1.createCriteria();
            criteria1.andEqualTo("orderId", orderId);
            List<OrderItem> orderItems = orderItemMapper.selectByExample(example1);
            //还原库存
            for (int j = 0; j < orderItems.size(); j++) {
                OrderItem orderItem = orderItems.get(j);
                //修改
                ProductSku productSku = productSkuMapper.selectByPrimaryKey(orderItem.getSkuId());
                //productSku.setSkuId(orderItem.getSkuId());
                productSku.setStock(productSku.getStock() + orderItem.getBuyCounts());
                productSkuMapper.updateByPrimaryKey(productSku);

            }
        }

    }
}
